package com.sgl.controller;


import com.sgl.config.googleSecurity.GoogleAuthenticatorUtil;
import com.sgl.config.shiro.ShiroUtil;
import com.sgl.entity.User;
import com.sgl.entity.UserDTO;
import com.sgl.service.DictService;
import com.sgl.service.UserService;
import com.sgl.util.PageBean;
import com.sgl.util.ReturnData;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;



/**
*	@author yanzheng_Yu
*	@date 2019年1月20日
*/
@RestController
@RequestMapping("user")
public class UserbgController {
	
	@Autowired
	private UserService userService;

	@Autowired
	DictService dictService;

	@Autowired
	private freemarker.template.Configuration configuration;

	private static final Log log = LogFactory.getLog(UserbgController.class);

	@PostMapping("login")
	public ReturnData login(UserDTO userDTO) throws TemplateModelException {
		ReturnData rd = new ReturnData();
		if(StringUtils.isBlank(userDTO.getNickname())) {
			return rd.failBack("用户名密码错误");
		}
		try{
			Subject subject = SecurityUtils.getSubject();

			UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getNickname(), userDTO.getPassword());

			subject.login(token);

			if (StringUtils.isNotEmpty(userDTO.getCode())){
				String key = ShiroUtil.getUser().getGoogleKey();
				long time = System.currentTimeMillis ();
				GoogleAuthenticatorUtil g = new GoogleAuthenticatorUtil();
				boolean result = g.check_code (key,userDTO.getCode(),time);
				if (!result){
					this.logout();
					return rd.failBack("安全码错误请重新输入");
				}
			}

		}catch (UnknownAccountException e) {
			return rd.failBack(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return rd.failBack("账号或密码不正确");
		}catch (LockedAccountException e) {
			return rd.failBack("账号已被锁定,请联系管理员");
		}catch (AuthenticationException e) {
			return rd.failBack("账户验证失败");
		}
		if (ShiroUtil.getUser().getRole()==2&&userDTO.getStatus()==null){
			this.logout();
			return new ReturnData(-1,0,"谷歌验证");
		}
		log.info(ShiroUtil.getUser().getBgLoginName()+"登陆成功");
		String seniorNoticeAmount=dictService.findByKeywords("seniorAdministrator").getValue();
		String generalNoticeAmount=dictService.findByKeywords("generalAdministrator").getValue();
		configuration.setSharedVariable("seniorNoticeAmount", seniorNoticeAmount);
		configuration.setSharedVariable("generalNoticeAmount", generalNoticeAmount);
		return rd.okBack();
	}

	@RequestMapping("findList")
	public ReturnData findList(PageBean<User> pageBean,String name,String phone) {
		HashMap<String, Object> param = new HashMap<String, Object>();

		User user=ShiroUtil.getUser();
		//		System.out.println(user);
		if (user!=null){
			param.put("role", user.getRole());
		}
		if(StringUtils.isNotBlank(name)) {
			param.put("name", name);
		}
		if (StringUtils.isNotBlank(phone)){
			param.put("phone", phone);
		}
		pageBean.setParam(param);
		List<User> list = userService.findList(pageBean);
		int count = userService.countList(pageBean);
		pageBean.setContent(list);
		pageBean.setTotalCount(count);



		return new ReturnData().okBack(pageBean);
	}

	
	
	/*@RequestMapping("findList")
	public ReturnData findList(PageBean<UserDTO> pageBean, String nickname, String phone) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(nickname)) {
			param.put("nickname", nickname);
		}
		if (StringUtils.isNotBlank(phone))
		{
			param.put("phone", phone);
		}
		pageBean.setParam(param);
		List<UserDTO> users = userService.findList(pageBean);
		int count = userService.countList(pageBean);

		pageBean.setContent(users);
		pageBean.setTotalCount(count);
		return new ReturnData().okBack(pageBean);
	}*/



//	@PostMapping("findListm")
//	public ReturnData findListByUserId(Long userId){
//		if (userId==null){
//			return new ReturnData().failBack("电话号码为空");
//		}
//		return userService.findByIdm(userId);
//	}
	
	@PostMapping("updateUserRole")
	public ReturnData updateUserRole(User userRoleDTO){
		User user=ShiroUtil.getUser();

		if (userRoleDTO.getRole()==2||userRoleDTO.getRole()==3){
			if (user.getRole()==2&&userRoleDTO.getRole()!=3){
				return userService.updateUserRole(userRoleDTO);
			}
			return new ReturnData().failBack("您无权修改该管理员的权限");
		}
		return userService.updateUserRole(userRoleDTO);
	}

	@GetMapping("logout")
	public ReturnData logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return new ReturnData().okBack();
	}
	
	@PostMapping("updateUserStatus")
	public ReturnData updateUserStatus(String userIdList){
		if (StringUtils.isNotBlank(userIdList)){
			String[] userIdArray = userIdList.split(",");
			int count = userService.updateUserStatus(userIdArray);
			if(count > 0) {
				return new ReturnData().okBack();
			}
		} 
		return new ReturnData().failBack("没有选中需要删除的信息！");
	}

	@PostMapping("add")
	public ReturnData add(User user) {

		User u = userService.findByBgLoginName(user.getBgLoginName());
		if(u != null) {
			return new ReturnData().failBack("登录已存在");
		}
		User nowUser=ShiroUtil.getUser();
		if (nowUser.getRole()==1||nowUser.getRole()==3){
			if (nowUser.getRole()!=user.getRole()){
				return new ReturnData().failBack("您无此操作权限！");
			}
		}else if (nowUser.getRole()==2){
			if (user.getRole()==3){
				return new ReturnData().failBack("您无此操作权限！");
			}
			if (user.getRole()==2){
				user.setGoogleKey(GoogleAuthenticatorUtil.generateSecretKey());
				user.setQrCode(GoogleAuthenticatorUtil.getQRBarcode(user.getBgLoginName(),user.getGoogleKey()));
			}
		}
		user.setNickname(user.getNickname());
		user.setOpenid(RandomStringUtils.randomAlphanumeric(20));
		user.setBgSalt(RandomStringUtils.randomAlphanumeric(20));
		user.setBgPassword(ShiroUtil.sha256(user.getBgPassword(),user.getBgSalt()));
		int count = userService.insert(user);
		if(count > 0) {
			return new ReturnData().okBack();
		}
		return new ReturnData().failBack("添加失败");
	}

//	@PostMapping("updatePassword")
//	public ReturnData updatePassword(String oldPassword,String password) {
//		User user = ShiroUtil.getUser();
//		if(! user.getBgPassword().equals(ShiroUtil.sha256(oldPassword,user.getBgSalt()))) {
//			return new ReturnData().failBack("原密码错误");
//		}
//		user.setBgSalt(RandomStringUtils.randomAlphanumeric(20));
//		user.setBgPassword(ShiroUtil.sha256(password,user.getBgSalt()));
//
//		int count = userService.updatePassword(user);
//		if(count > 0) {
//			return new ReturnData().okBack();
//		}
//		return new ReturnData().failBack("修改失败");
//	}
//
//	@RequestMapping("findByRole")
//	public ReturnData findByRole(Integer role) {
//		List<User> users = userService.findByRole(role) ;
//		return new ReturnData().okBack(users);
//	}
//
//	@RequestMapping("findUserPoint")
//	public ReturnData findUserPoint(PageBean<UserPointDTO> pageBean, String nickname, String phone,String pointType){
//		HashMap<String, Object> param = new HashMap<String, Object>();
//		if(StringUtils.isNotBlank(nickname)) {
//			param.put("nickname", nickname);
//		}
//		if (StringUtils.isNotBlank(phone)) {
//			param.put("phone", phone);
//		}
//		if (StringUtils.isNotBlank(pointType)){
//			param.put("pointType",pointType);
//		}
//		pageBean.setParam(param);
//		List<UserPointDTO> users = userService.findUserPointList(pageBean);
//		int count = userService.countUserPointList(pageBean);
//
//		pageBean.setContent(users);
//		pageBean.setTotalCount(count);
//		return new ReturnData().okBack(pageBean);
//	}
//
////	addPointLog
//	@PostMapping("addPointLog")
//	public ReturnData addPointLog(UserPointDTO userPointDTO){
//		User user=userService.findByPhone(userPointDTO.getPhone());
//		if (user==null){
//			return new ReturnData().failBack("没有该用户，请重新填写电话");
//		}
//		if (user.getPoint()<userPointDTO.getPoint()&&userPointDTO.getType()==2){
//			return new ReturnData().failBack("当前用户积分不足");
//		}
//		userPointDTO.setCurrentPoint(user.getPoint());
//		userPointDTO.setUserId(user.getId());
////		System.out.println(userPointDTO);
//		return userService.addUserPoint(userPointDTO);
//	}
//
//	@PostMapping("findStatisticsData")
//	public ReturnData statisticsData(){
//		User user=ShiroUtil.getUser();
//		System.out.println(user);
//		return userService.statisticsData(user);
//	}
//	@PostMapping("findRecentMonth")
//	public ReturnData recentMonth(){
//		User user=ShiroUtil.getUser();
//		System.out.println(user);
//		return userService.recentMonth(user);
//	}


}
